<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { modalFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { SpuModule } = mcApi;
  const { BizMetaArrApi } = SpuModule;

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: modalFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const ifUpdate = ref<boolean>(false);
  const listKeys: string[] = ['conditionList', 'supportedResultList', 'unsupportedResultList'];
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    await resetFields();
    const record = cloneDeep(data?.record || {});
    ifUpdate.value = !!data.ifUpdate;
    setModalProps({
      minHeight: 50,
      confirmLoading: false,
      title: `${unref(ifUpdate) ? '编辑' : '新增'}业务元属性规则`,
    });
    if (unref(ifUpdate)) {
      listKeys.forEach((key: string) => {
        const target = record[key];
        record[key] = handleInitTreeData(target);
      });
      await setFieldsValue(record);
    }
  });
  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      setModalProps({ confirmLoading: true });
      const values: any = await validate();
      listKeys.forEach((key: string) => {
        const target = values[key];
        values[key] = handlePostTreeData(target);
      });
      const fun = unref(ifUpdate)
        ? BizMetaArrApi.updateBizMetaAttrRule
        : BizMetaArrApi.createBizMetaAttrRule;
      await fun(values);
      createMessage.success(`${unref(ifUpdate) ? '编辑' : '新增'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  // 处理元属性初始数据
  function handleInitTreeData(list: any) {
    return (
      list?.map?.((item: any) => {
        const { cnName, bizMetaAttrId } = item;
        return {
          label: cnName,
          value: bizMetaAttrId,
        };
      }) || []
    );
  }
  // 处理元属性提交数据
  function handlePostTreeData(list: any) {
    return (
      list?.map?.((item: any) => {
        return { bizMetaAttrId: item.value };
      }) || []
    );
  }
</script>

<style scoped lang="less"></style>
